﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class GameController : MonoBehaviour {

    public GameObject startUI;
    public GameObject gameUI;

    /// <summary>
    /// 游戏计分
    /// </summary>
    public int sumScore = 0;

    /// <summary>
    /// 显示分数的对象
    /// </summary>
    public GameObject txtScore;

    /// <summary>
    /// 游戏结束的提示
    /// </summary>
    public GameObject txtGameOver;

    /// <summary>
    /// 滑动器，用来倒计时
    /// </summary>
    public Slider sliderTimer;

    private float maxTimer = 60f;

    /// <summary>
    /// 计时器，一局游戏只能玩60秒
    /// </summary>
    public float timer;

    /// <summary>
    /// 单例模式
    /// </summary>
    public static GameController Instance;

    /// <summary>
    /// 存放方块
    /// </summary>
    public GameObject blockContainer;

    /// <summary>
    /// 方块的预设
    /// </summary>
    public GameObject[] blockPrefabs;

    /// <summary>
    /// 各个方块的分数
    /// </summary>
    public int[] blockScores;

    /// <summary>
    /// 使用1到100之间的数值，控制各种方块出现的几率
    /// </summary>
    public int[] blockOdds;

    /// <summary>
    /// 是否在游戏中
    /// </summary>
    private bool isGame = false;

    /// <summary>
    /// 存放所有初始化的方块
    /// </summary>
    private ArrayList blocks;

    void Awake()
    {        
        Instance = this;
        this.ReturnStartUI();
        this.timer = this.maxTimer;
        sliderTimer.maxValue = this.timer;
        sliderTimer.minValue = 0;
        sliderTimer.value = this.timer;
    }

    void Update()
    {
        if (isGame)
        {
            this.timer -= Time.deltaTime;
            sliderTimer.value = this.timer;
            if (this.timer <= 0)
            {
                txtGameOver.SetActive(true);
                Text txt = txtGameOver.GetComponent<Text>();
                txt.text = "Game Over. \r\n Score : " + this.sumScore;
                //延迟一会后返回主界面
                StartCoroutine(GameOver());
            }
        }
    }

    IEnumerator GameOver()
    {
        yield return new WaitForSeconds(3);
        ReturnStartUI();
    }


    public void EnterGameUI()
    {
        startUI.SetActive(false);
        gameUI.SetActive(true);
        txtScore.SetActive(true);
        sliderTimer.transform.gameObject.SetActive(true);
        txtGameOver.SetActive(false);
        this.isGame = true;
        this.sumScore = 0;//分数清零
        this.ShowScore(sumScore);
        this.timer = this.maxTimer;//重新计时
        sliderTimer.value = this.timer;
        this.StartGame();
    }

    public void ReturnStartUI()
    {
        startUI.SetActive(true);
        gameUI.SetActive(false);
        txtScore.SetActive(false);
        sliderTimer.transform.gameObject.SetActive(false);
        txtGameOver.SetActive(false);
        if (blocks != null)
        {
            for (int i = blocks.Count - 1; i >= 0; i--)
            {
                Block block = (Block)blocks[i];
                block.Destroy();
                blocks.RemoveAt(i);
            }
        }
        this.isGame = false;
    }
    
    private void StartGame()
    {
        this.blocks = new ArrayList();
        for (int i = 0; i < 4; i++)
        {
            //每行随机生成一个block
            this.AddBlock(i);
        }
    }

    private void AddBlock(int rowIndex)
    {
        //随机取得1到100之间的数值，与各个方块的数值范围比较，以确定生成那个方块
        int value = Random.Range(1, 100);        
        int index = -1;//随机数所在范围对应的索引
        for (int i = 0; i < blockOdds.Length; i++)
        {
            if (value <= blockOdds[i])
            {
                index = i;
                break;
            }
        }
        GameObject obj = Instantiate(blockPrefabs[index]) as GameObject;

        Block block = obj.GetComponent<Block>();
        block.score = blockScores[index];
        block.SetPosition(Random.Range(0, 4), rowIndex);
        block.transform.parent = blockContainer.transform;
        this.blocks.Add(block);
    }

    public void AddScore(int score)
    {
        sumScore += score;
        this.ShowScore(sumScore);
    }

    public void ShowScore(int score)
    {
        Text txt = txtScore.GetComponent<Text>();
        txt.text = score.ToString();
    }

    public void PlaySound()
    {
        this.audio.Play();
    }

    /// <summary>
    /// 点击方块后，所有方块下移，行索引小于1的销毁
    /// </summary>
    public void RemoveBlock(Block delBlock)
    {
        if (this.blocks == null || this.blocks.Count <= delBlock.rowIndex)
            return;

        //如果不是点击的最下方方块，则需要在消掉方块的一行再次添加一个方块        
        if (delBlock.rowIndex > 0)
        {
            this.AddBlock(delBlock.rowIndex);
        }
        //移除方块
        this.blocks.Remove(delBlock);
        delBlock.Destroy();
        //在上方增加一个方块
        this.AddBlock(4);
        //将所有方块向下移动一行
        for (int i = 0; i < this.blocks.Count; i++)
        {
            Block block = (Block)(this.blocks[i]);
            block.MoveDown();
            if (block.rowIndex < 0)
            {
                block.Destroy();
                blocks.RemoveAt(i);
                i--;
            }
        }
    }
}
